const { resolve } = require('path')
const util = require('util')
const fs = require('fs')

const readFileAsync = util.promisify(fs.readFile)

async function loadLanguage(ctx, next) {
    console.time('loadLanguage')
    let filePath = resolve(__dirname, '../views/language/index/zh_cn.json')

    console.log(filePath)

    let data = await readFileAsync(filePath, 'utf-8')

    if(data) {
        ctx.state.language = JSON.parse(data)
    } else {
        let errorMessage = '语言文件加载失败'
        console.error(errorMessage)
        ctx.throw(500, errorMessage)
    }

    console.log(data)

    console.timeEnd('loadLanguage')
    next()
}

module.exports = loadLanguage
